package com.hxzy.config;

import com.hxzy.interceptor.ContamerTokenValidateHandlerInterceptor;
import com.hxzy.interceptor.TokenValidateHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * mvc配置
 *
 * @author tonneyyy
 */
@Configuration
public class WaimaiWebConfig implements WebMvcConfigurer {





    /**
     * 本地资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //  file:///D:/image_server/1562328784508686336.png
       registry.addResourceHandler("/image/**").addResourceLocations(" file:///D:\\image_server\\");
    }

    /**
     * 后台放行的url
     */
    @Value(value = "${exclude.admin.urls}")
    private String[] excludeUrls;

    /**
     * 前端放行的url
     */
    @Value(value = "${exclude.front.urls}")
    private String[] excludeFrontUrls;

    /**
     * 后台用户拦截器
     */
    @Autowired
    private TokenValidateHandlerInterceptor  tokenValidateHandlerInterceptor;

    /**
     * 前端用户拦截器
     */
    @Autowired
    private ContamerTokenValidateHandlerInterceptor contamerTokenValidateHandlerInterceptor;
    /**
     * 自定义定义拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册后台拦截器
        registry.addInterceptor(tokenValidateHandlerInterceptor).addPathPatterns("/api/**").excludePathPatterns(excludeUrls);

        //注册前端拦截器
        registry.addInterceptor(contamerTokenValidateHandlerInterceptor).addPathPatterns("/front/user/**","/front/order/**").excludePathPatterns(excludeFrontUrls);


    }


    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);

        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

}
